import Vue from "vue";
export const $bus = new Vue();
window.$bus = $bus;
// 事件监听，在组件销毁的时候会自动off事件
export default {
  install(V) {
    V.prototype.$bus = $bus;
    V.mixin({
      data() {
        return {
          selfEvents: {},
          selfOnceEvents: {}
        };
      },
      methods: {
        $_on(key, fn, { immediate } = {}) {
          if (!this.selfEvents[key]) {
            this.selfEvents[key] = [fn];
          } else {
            this.selfEvents[key].push(fn);
          }
          $bus.$on(key, fn);
          if (immediate) {
            // 是否立即执行
            fn();
          }
        },
        $_once(key, fn) {
          if (!this.selfOnceEvents[key]) {
            this.selfOnceEvents[key] = [fn];
          } else {
            this.selfOnceEvents[key].push(fn);
          }
          $bus.$on(key, fn);
        },
        $_emit(key, ...rest) {
          $bus.$emit(key, ...rest);
          if (this.selfOnceEvents[key]) {
            this.selfOnceEvents[key] = null;
          }
        },
        $_off(...rest) {
          $bus.$off(...rest);
        }
      },
      destroyed() {},
      beforeDestroy() {
        const clearEvent = (obj) => {
          Object.keys(obj).forEach((key) => {
            if (obj[key]) {
              obj[key].forEach((fn) => {
                $bus.$off(key, fn);
              });
            }
          });
        };
        clearEvent(this.selfOnceEvents);
        clearEvent(this.selfEvents);
      }
    });
  }
};
